<?php
/**
 * 配置表模型
 */

namespace app\common\model;

use think\model\concern\SoftDelete;

class SysConfig extends Model
{
    protected $name = 'sys_config'; // 当前模型对应的完整数据表名称
    protected $autoWriteTimestamp = true; // 开启自动写入时间戳

    //可搜索字段
    protected $searchField = ['name',];

    /**
     * Desc: 设置配置值
     * @param $type
     * @param $name
     * @param $value
     */
    public static function set($type, $name, $value)
    {
        $original = $value;
        $update_time = time();
        if (is_array($value)) {
            $value = json_encode($value, true);
        }
        $data = self::where(['type' => $type, 'name' => $name])
            ->find();
        if (empty($data)) {
            (new SysConfig)->insert(['type' => $type, 'name' => $name, 'value' => $value]);
        } else {
            self::where(['type' => $type, 'name' => $name])
                ->update(['value' => $value, 'update_time' => $update_time]);
        }
        return $original;
    }

    /**
     * Desc: 获取配置值
     * @param $type
     * @param $name
     * @param string $default_value
     * @return mixed|string
     */
    public static function get($type, $name = '',  $default_value = null)
    {
        $value = self::where(['type' => $type, 'name' => $name])->value('value');
        $json = json_decode($value, true);
        if (json_last_error() === JSON_ERROR_NONE) {
            $value = $json;
        }
        if ($value) {
            return $value;
        }
    }
}
